package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.pojo.TOrder;
import com.bwie.pojo.TUser;
import com.bwie.pojo.TbOrderDetail;
import com.bwie.service.IUserService;
import com.bwie.service.TOrderService;
import com.bwie.mapper.TOrderMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.TbProdVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

/**
 * @author lenovo
 * @description 针对表【t_order】的数据库操作Service实现
 * @createDate 2025-03-21 19:04:09
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder>
        implements TOrderService {

    @Autowired
    private TOrderMapper tOrderMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IUserService iUserService;


    @Autowired
    HttpServletRequest request;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Override
    public R getOrderById(Integer id) {
        TOrder tOrder = tOrderMapper.selectById(id);

        if (tOrder == null) {
            return R.ERROR(500, "订单不存在");
        }

//        //获取用户信息
//        String url = "http://localhost:9001/user/index/getUserById/" + tOrder.getUserId();
//        R r = restTemplate.postForObject(url, null, R.class);

        R r = iUserService.getUserById(tOrder.getUserId());
        if (r.getCode() != 200) {
            return r;
        }
        //需要把R类的Data转换成字符串
        String data = JSON.toJSONString(r.getData());
        TUser tUser = JSON.parseObject(data, TUser.class);

        tOrder.setUser(tUser);

        return R.OK(tOrder);
    }

    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {

        //构造分页查询数据
        Page<TOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //获取分页数据
        Page<TOrder> list = tOrderMapper.getOrderList(page);

        //返回数据
        return R.OK(list);
    }

    @Override
    public R addOrder(List<TbProdVo> prodVoList) {


        //获取用户ID
        String token = request.getHeader("token");
        if (token == null) {
            return R.ERROR(500, "请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("id", Integer.class);

        //判断商品是否有效
        BigDecimal totalAmount = new BigDecimal(0.0);
        Integer totalNum = 0;
        for (TbProdVo tbProdVo : prodVoList) {
            if (tbProdVo.getProdStatus() != 2) {
                return R.ERROR(500, "商品失效");
            }
            BigDecimal multiply = tbProdVo.getProdPrice().multiply(new BigDecimal(tbProdVo.getBuyNum()));
            totalAmount = totalAmount.add(multiply);

            totalNum += tbProdVo.getBuyNum();
        }

        //判断库存\减少库存
        for (TbProdVo tbProdVo : prodVoList) {
            if (tbProdVo.getBuyNum() > tbProdVo.getProdStock()) {
                return R.ERROR(500, "库存不足");
            }
        }


        //生成订单
        TOrder order = new TOrder();
        order.setId(userId);

        String code = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        code += RandomUtil.randomNumbers(4);
        order.setCode(code);
        order.setCreateTime(new Date());
        order.setStatus(0);
        order.setAmount(totalAmount);
        order.setCount(totalNum);
        tOrderMapper.insert(order);

        //生成订单明细
        for (TbProdVo tbProdVo : prodVoList) {
            TbOrderDetail detail = new TbOrderDetail();
            detail.setOrderId(tbProdVo.getProdId());
            detail.setProdId(tbProdVo.getProdId());
            detail.setProdNum(tbProdVo.getBuyNum());
            detail.setProdPrice(tbProdVo.getProdPrice());

            tbOrderDetailMapper.insert(detail);
        }
        return R.OK();
    }


}




